/**
 * 本地存储工具类
 * 统一管理 localStorage
 */

export const storage = {
  // 设置存储
  set(key: string, value: any): void {
    try {
      const data = JSON.stringify(value);
      uni.setStorageSync(key, data);
    } catch (error) {
      console.error('存储数据失败:', error);
    }
  },

  // 获取存储
  get<T = any>(key: string): T | null {
    try {
      const data = uni.getStorageSync(key);
      if (data) {
        return JSON.parse(data) as T;
      }
      return null;
    } catch (error) {
      console.error('读取数据失败:', error);
      return null;
    }
  },

  // 删除存储
  remove(key: string): void {
    uni.removeStorageSync(key);
  },

  // 清空所有存储
  clear(): void {
    uni.clearStorageSync();
  },

  // 用户相关存储
  user: {
    setToken(token: string) {
      storage.set('token', token);
    },
    getToken(): string | null {
      return storage.get<string>('token');
    },
    setUserInfo(userInfo: any) {
      storage.set('userInfo', userInfo);
    },
    getUserInfo<T = any>(): T | null {
      return storage.get<T>('userInfo');
    },
    setLogin(isLogin: boolean) {
      storage.set('isLogin', isLogin);
    },
    isLogin(): boolean {
      return storage.get<boolean>('isLogin') || false;
    },
    clearUserData() {
      storage.remove('token');
      storage.remove('userInfo');
      storage.remove('isLogin');
    }
  }
};